<template>
	<view class="inventory-form-container">
		<view class="form-header">
			<text class="form-title">物品入库单</text>
			<text class="form-subtitle">请填写物品入库信息</text>
		</view>

		<view class="form-section">
			<view class="section-title">采购入库基本信息</view>
			
			<view class="form-item">
				<text class="form-label">入库单号 <text class="required">*</text></text>
				<input class="form-input" v-model="inventoryData.inventory_no" placeholder="系统自动生成" disabled />
			</view>

			<view class="form-item">
				<text class="form-label">采购完成日期 <text class="required">*</text></text>
				<DateTimePicker v-model="inventoryData.purchase_complete_date" mode="date" />
			</view>

			<view class="form-item">
				<text class="form-label">入库日期 <text class="required">*</text></text>
				<DateTimePicker v-model="inventoryData.inventory_date" mode="date" />
			</view>

			<view class="form-item">
				<text class="form-label">仓库位置 <text class="required">*</text></text>
				<input class="form-input" v-model="inventoryData.warehouse_location" placeholder="请输入仓库位置" />
			</view>

			<view class="form-item">
				<text class="form-label">采购人员 <text class="required">*</text></text>
				<input class="form-input" v-model="inventoryData.purchaser" placeholder="请输入采购人员姓名" />
			</view>

			<view class="form-item">
				<text class="form-label">入库人员 <text class="required">*</text></text>
				<input class="form-input" v-model="inventoryData.inventory_person" placeholder="请输入入库人员姓名" />
			</view>

			<view class="form-item textarea-item">
				<text class="form-label">采购备注</text>
				<textarea class="form-textarea" v-model="inventoryData.purchase_remark" placeholder="请输入采购过程中的备注信息" maxlength="200"></textarea>
				<text class="char-count">{{ inventoryData.purchase_remark.length }}/200</text>
			</view>

			<view class="form-item textarea-item">
				<text class="form-label">入库备注</text>
				<textarea class="form-textarea" v-model="inventoryData.remark" placeholder="请输入入库备注信息" maxlength="200"></textarea>
				<text class="char-count">{{ inventoryData.remark.length }}/200</text>
			</view>
		</view>

		<view class="form-section">
			<view class="section-header">
				<text class="section-title">入库物品清单</text>
				<view class="add-item-button" @tap="addInventoryItem">
					<text class="add-icon">+</text>
					<text class="add-text">添加物品</text>
				</view>
			</view>
			
			<view class="inventory-item" v-for="(item, index) in inventoryData.items" :key="index">
				<view class="item-header">
					<text class="item-title">物品 {{ index + 1 }}</text>
					<text class="item-delete" @tap="deleteInventoryItem(index)">×</text>
				</view>
				
				<view class="form-item">
					<text class="form-label">物品名称 <text class="required">*</text></text>
					<input class="form-input" v-model="item.name" placeholder="请输入物品名称" />
				</view>

				<view class="form-item">
					<text class="form-label">规格参数 <text class="required">*</text></text>
					<input class="form-input" v-model="item.specification" placeholder="请输入规格参数" />
				</view>

				<view class="form-item">
					<text class="form-label">入库数量 <text class="required">*</text></text>
					<input class="form-input" type="number" v-model="item.quantity" placeholder="请输入入库数量" />
				</view>
				
				<view class="form-item">
					<text class="form-label">单位 <text class="required">*</text></text>
					<input class="form-input" v-model="item.unit" placeholder="请输入单位" />
				</view>

				<view class="form-item">
					<text class="form-label">实际单价 <text class="required">*</text></text>
					<input class="form-input" type="digit" v-model="item.unit_price" placeholder="请输入实际单价" />
				</view>

				<view class="form-item">
					<text class="form-label">供应商 <text class="required">*</text></text>
					<input class="form-input" v-model="item.supplier" placeholder="请输入供应商名称" />
				</view>

				<view class="form-item">
					<text class="form-label">物品状态 <text class="required">*</text></text>
					<picker @change="(e: any) => onItemStatusChange(e, index)" :value="item.statusIndex" :range="itemStatusOptions">
						<view class="picker-input">
							<text>{{ itemStatusOptions[item.statusIndex] }}</text>
							<text class="picker-arrow">></text>
						</view>
					</picker>
				</view>

				<view class="form-item textarea-item">
					<text class="form-label">物品备注</text>
					<textarea class="form-textarea" v-model="item.remark" placeholder="请输入物品备注" maxlength="100"></textarea>
					<text class="char-count">{{ item.remark.length }}/100</text>
				</view>
			</view>
		</view>

		<view class="form-section">
			<view class="section-title">附件上传</view>
			<view class="upload-area">
				<view class="uploaded-files" v-if="uploadedFiles.length > 0">
					<view class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
						<text class="file-name">{{ file.name }}</text>
						<text class="file-size">{{ formatFileSize(file.size) }}</text>
						<text class="delete-btn" @tap="removeFile(index)">×</text>
					</view>
				</view>
				<button class="upload-btn" @tap="chooseFile">选择文件</button>
			</view>
		</view>

		<view class="form-summary">
			<view class="summary-item">
				<text class="summary-label">物品总数：</text>
				<text class="summary-value">{{ totalItems }}</text>
			</view>
			<view class="summary-item">
				<text class="summary-label">入库总金额：</text>
				<text class="summary-value">¥{{ totalAmount }}</text>
			</view>
		</view>

		<view class="form-actions">
			<button class="btn btn-cancel" @tap="handleCancel">取消</button>
			<button class="btn btn-submit" @tap="handleSubmit" :disabled="!canSubmit()">提交入库</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import DateTimePicker from '@/components/DateTimePicker.vue'
import { formatFileSize, uploadAttachments } from '@/common/upload'
import { getCurrentUser } from '@/common/auth'

// 定义接口
interface InventoryItem {
	name: string
	specification: string
	quantity: string
	unit: string
	unit_price: string
	supplier: string
	status: string
	statusIndex: number
	remark: string
}

interface InventoryData {
	inventory_no: string
	purchase_complete_date: string
	inventory_date: string
	warehouse_location: string
	purchaser: string
	inventory_person: string
	purchase_remark: string
	remark: string
	items: InventoryItem[]
}

// 物品状态选项
const itemStatusOptions = ['完好', '轻微损坏', '严重损坏', '需要维修']

// 表单数据
const inventoryData = ref<InventoryData>({
	inventory_no: '',
	purchase_complete_date: '',
	inventory_date: '',
	warehouse_location: '',
	purchaser: '',
	inventory_person: '',
	purchase_remark: '',
	remark: '',
	items: [{
		name: '',
		specification: '',
		quantity: '',
		unit: '',
		unit_price: '',
		supplier: '',
		status: '完好',
		statusIndex: 0,
		remark: ''
	}]
})

const uploadedFiles = ref<any[]>([])

// 计算属性
const totalItems = computed(() => {
	return inventoryData.value.items.reduce((total, item) => {
		return total + (parseFloat(item.quantity) || 0)
	}, 0)
})

const totalAmount = computed(() => {
	return inventoryData.value.items.reduce((total, item) => {
		const quantity = parseFloat(item.quantity) || 0
		const unitPrice = parseFloat(item.unit_price) || 0
		return total + (quantity * unitPrice)
	}, 0).toFixed(2)
})

// 生成入库单号
const generateInventoryNo = () => {
	const date = new Date()
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
	inventoryData.value.inventory_no = `RK${year}${month}${day}${random}`
}

// 添加物品
const addInventoryItem = () => {
	inventoryData.value.items.push({
		name: '',
		specification: '',
		quantity: '',
		unit: '',
		unit_price: '',
		supplier: '',
		status: '完好',
		statusIndex: 0,
		remark: ''
	})
}

// 删除物品
const deleteInventoryItem = (index: number) => {
	if (inventoryData.value.items.length > 1) {
		inventoryData.value.items.splice(index, 1)
	}
}

// 物品状态变更
const onItemStatusChange = (e: any, index: number) => {
	const statusIndex = e.detail.value
	inventoryData.value.items[index].statusIndex = statusIndex
	inventoryData.value.items[index].status = itemStatusOptions[statusIndex]
}

// 选择文件
const chooseFile = () => {
	uni.chooseFile({
		count: 5,
		extension: ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx', '.xls', '.xlsx'],
		success: (res: UniApp.ChooseFileSuccessCallbackResult) => {
			if (Array.isArray(res.tempFiles)) {
				uploadedFiles.value = [...uploadedFiles.value, ...res.tempFiles]
			} else {
				uploadedFiles.value = [...uploadedFiles.value, res.tempFiles]
			}
		},
		fail: (err: UniApp.GeneralCallbackResult) => {
			console.error('选择文件失败:', err)
			uni.showToast({
				title: '选择文件失败',
				icon: 'none'
			})
		}
	})
}

// 删除文件
const removeFile = (index: number) => {
	uploadedFiles.value.splice(index, 1)
}

// 上传文件
const uploadAllFiles = async (): Promise<string[]> => {
	if (uploadedFiles.value.length === 0) return []
	
	const fileUrls: string[] = []	
	
	try {
		const uploadedResults = await uploadAttachments(
			uploadedFiles.value,
			true,
			{
				type: "attachment",
				relation_id: inventoryData.value.inventory_no, // 传递申请ID
				relation_type: "inventory", // 传递申请类型	
			},
			(current, total) => {
				console.log(`上传进度: ${current}/${total}`)
			}
		)
		
		uploadedResults.forEach(file => {
			if (file && file.url) {
				fileUrls.push(file.url)
			}
		})
		
		return fileUrls
	} catch (error) {
		console.error('上传文件失败:', error)
		uni.showToast({
			title: '文件上传失败',
			icon: 'none'
		})
		return []
	}
}

// 验证表单
const canSubmit = (): boolean => {
	const data = inventoryData.value
	
	// 检查基本信息
	if (!data.purchase_complete_date || !data.inventory_date || 
		!data.warehouse_location || !data.purchaser || !data.inventory_person) {
		return false
	}
	
	// 检查物品信息
	for (const item of data.items) {
		if (!item.name || !item.specification || !item.quantity || 
			!item.unit || !item.unit_price || !item.supplier) {
			return false
		}
	}
	
	return true
}

// 提交入库
const handleSubmit = async () => {
	if (!canSubmit()) {
		uni.showToast({
			title: '请完善所有必填信息',
			icon: 'none'
		})
		return
	}
	
	try {
		// 上传附件
		const attachmentUrls = await uploadAllFiles()
		
		// 准备提交数据
		const submitData = {
			...inventoryData.value,
			attachments: attachmentUrls,
			total_amount: totalAmount.value,
			total_items: totalItems.value
		}
		
		// 触发提交事件
		emit('submit', submitData)
		
	} catch (error) {
		console.error('提交入库失败:', error)
		uni.showToast({
			title: '提交失败，请稍后重试',
			icon: 'none'
		})
	}
}

// 取消操作
const handleCancel = () => {
	emit('cancel')
}

// 定义事件
const emit = defineEmits<{
	submit: [data: any]
	cancel: []
}>()

// 初始化
onMounted(() => {
	generateInventoryNo()
	// 设置默认日期为今天
	const today = new Date()
	const year = today.getFullYear()
	const month = String(today.getMonth() + 1).padStart(2, '0')
	const day = String(today.getDate()).padStart(2, '0')
	const todayStr = `${year}-${month}-${day}`
	
	inventoryData.value.purchase_complete_date = todayStr
	inventoryData.value.inventory_date = todayStr
	
	// 设置默认采购人员和入库人员为当前用户
	const currentUser = getCurrentUser()
	if (currentUser && currentUser.name) {
		inventoryData.value.purchaser = currentUser.name
		inventoryData.value.inventory_person = currentUser.name
	}
})
</script>

<style scoped>
.inventory-form-container {
	padding: 20rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
}

/* 在弹窗中的样式调整 */
:deep(.inventory-form-container) {
	min-height: auto;
	background-color: #fff;
}

.form-header {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.form-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.form-subtitle {
	font-size: 26rpx;
	color: #666;
}

.form-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.add-item-button {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 12rpx 16rpx;
	background-color: #2B5BA1;
	color: white;
	border-radius: 8rpx;
	font-size: 26rpx;
}

.add-icon {
	font-size: 28rpx;
	font-weight: bold;
}

.form-item {
	margin-bottom: 20rpx;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
	display: block;
}

.required {
	color: #f44336;
}

.form-input {
	width: 100%;
	height: 80rpx;
	background-color: #fafafa;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 0 16rpx;
	font-size: 28rpx;
}

.picker-input {
	width: 100%;
	height: 80rpx;
	background-color: #fafafa;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 0 16rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.picker-arrow {
	color: #999;
}

.textarea-item .form-textarea {
	width: 100%;
	height: 160rpx;
	background-color: #fafafa;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 16rpx;
	font-size: 28rpx;
	resize: none;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
}

.inventory-item {
	background-color: #fafafa;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid #e0e0e0;
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.item-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.item-delete {
	font-size: 32rpx;
	color: #f44336;
	padding: 4rpx 8rpx;
}

.upload-area {
	margin-top: 12rpx;
}

.uploaded-files {
	margin-bottom: 16rpx;
}

.file-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12rpx;
	background-color: #fafafa;
	border-radius: 8rpx;
	margin-bottom: 8rpx;
}

.file-name {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.file-size {
	font-size: 24rpx;
	color: #666;
	margin: 0 12rpx;
}

.delete-btn {
	font-size: 28rpx;
	color: #f44336;
	padding: 4rpx 8rpx;
}

.upload-btn {
	background-color: #f0f0f0;
	color: #666;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 16rpx 24rpx;
	font-size: 28rpx;
}

.form-summary {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.summary-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.summary-item:last-child {
	margin-bottom: 0;
}

.summary-label {
	font-size: 28rpx;
	color: #666;
}

.summary-value {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.form-actions {
	display: flex;
	gap: 20rpx;
	padding: 20rpx 0;
}

.btn {
	flex: 1;
	padding: 24rpx 20rpx;
	border-radius: 8rpx;
	font-size: 30rpx;
	font-weight: bold;
	border: none;
}

.btn-cancel {
	background-color: #f0f0f0;
	color: #666;
}

.btn-submit {
	background-color: #2B5BA1;
	color: white;
}

.btn-submit:disabled {
	background-color: #ccc;
	color: #999;
}
</style> 